﻿#include "notifyevent.h"

QMap<NotifyType,QList<std::pair<NotifyEvent::notify_event_func,void*>>> NotifyEvent::s_notifys;
QReadWriteLock *NotifyEvent::s_lock=new QReadWriteLock();


void NotifyEvent::add(NotifyType type,notify_event_func func,void* context){
    QWriteLocker locker(s_lock);
    s_notifys[type].push_back(std::make_pair(func, context));
}


void NotifyEvent::remove(notify_event_func func,void *context){
    QWriteLocker locker(s_lock);
    for (auto it = s_notifys.begin(); it != s_notifys.end(); ++it) {
        auto funcIt = std::remove_if(it.value().begin(), it.value().end(),\
                                     [=](const std::pair<notify_event_func, void*>& p) -> bool {
            if (p.first == func && p.second == context) {
                return true;
            }
            else {
                return false;
            }
        });
        it.value().erase(funcIt, it.value().end());
    }
}
void NotifyEvent::notify(NotifyType type, int event, void* data)
{
    QList<std::pair<notify_event_func, void*>> funs;

    {
        QReadLocker locker(s_lock);
        auto it = s_notifys.find(type);
        if (it == s_notifys.end()) {
            //            qDebug() << __FUNCTION__ << GetCurrentThreadId() << "end";
            return;
        }
        funs = *it;
    }


    for (auto it = funs.begin(); it != funs.end(); ++it) {
        if (it->first) {
            it->first(event, data, it->second);
        }
    }
}

void NotifyEvent::notify(int event, void* data /*= nullptr*/)
{
    notify(NOTIFY_DEFAULT_CTRL, event, data);
}


void NotifyEvent::clear()
{

    QWriteLocker locker(s_lock);
    s_notifys.clear();
}


